<template>
	<view class="page">
		<!-- 顶部切换 -->
		<view class="tabsBox" id="main1">
			<!-- <u-tabs :list="tabsList" @click="switchTabs" :activeStyle="{ color: '#14AAA8 ' }" itemStyle="{width:365rpx;height:100rpx}"
				lineColor="#14AAA8 "></u-tabs> -->
			<!-- 1 新机  2 旧机 -->
			<view :class="[new_machine == 1 ? 'tabItemClass' : ''] " class="tabItem" @click="switchTabs(1)">
				新机
				<view class="activeBox" v-show="new_machine == 1">
				</view>
			</view>
			<view :class="[new_machine == 2 ? 'tabItemClass' : ''] " class="tabItem" @click="switchTabs(2)">
				旧机
				<view class="activeBox" v-show="new_machine == 2">
				</view>
			</view>
		</view>
		<!-- 主体 -->
		<!-- 测试 -->
		<scroll-view scroll-y="true" class="scroll-Y" :style="'height:'+scrollviewHigh+'px;'">
			<view class="oldBox">
				<view class="mainBox" style="height: 380rpx;" >
					<view class="title">
						商品信息
					</view>
					<!-- 品牌 -->
					<view class="">
						<picker @change="changeBrand($event)" data-info="品牌" :value="brandVal" :range="brandCol"
							:range-key="'name'">
							<view class="infoItem">
								<view class="">
									品牌：
								</view>
								<view class="rightText">
									{{brandName}}
								</view>
							</view>
						</picker>
					</view>
					<!-- 型号 -->
					<view class="">
						<picker @change="changeModel($event)" data-info="型号" :value="modelVal" :range="modelCol"
							:range-key="'model'" :disabled="brandName=='请选择品牌'">
							<view class="infoItem">
								<view class="">
									型号
								</view>
								<view class="rightText">
									{{modelName}}
								</view>
							</view>
						</picker>
					</view>
					<!-- 内存 -->
					<view class="">
						<picker @change="changeMemory($event)" data-info="内存" :value="memoryVal" :range="memoryCol"
							:range-key="'memory'" :disabled="brandName=='请选择品牌'">
							<view class="infoItem">
								<view class="">
									内存
								</view>
								<view class="rightText">
									{{memoryName}}
								</view>
							</view>
						</picker>
					</view>
				</view>
				<view class="mainBox" style="450rpx">
					<view class="title">
						优惠金额
					</view>
					<view class="">
						<view class="infoItem">
							<view class="">
								售价
							</view>
							<view class="" style="display: flex;">
								<input type="number" placeholder="请输入售价" v-model="price" @blur="blurPrice"
									style="font-size: 25rpx;width: 150rpx;background-color: #f6f6f6;" />
							</view>

							<view class="guideText">
								指导价：
							</view>
							<span style="color: red;" v-if="guide_price">￥{{guide_price}}</span>
							<span v-else style="color: red;">请选择指导价</span>
						</view>
						<view class="tip" v-if="ceiling_price">
							请填写给予用户的售价<span style="color: #807D7C;">（价格≤{{ceiling_price}}元有效）</span>
						</view>
						<view class="tip" v-else>
							请填写给予用户的售价<span style="color: #807D7C;">（价格≤0元有效）</span>
						</view>
					</view>
					<!-- 花呗总额度 -->
					<view class="">
						<view class="priceItem">
							<view class="Pitem">
								<view class="">
									下单人花呗总额度：
								</view>
								<view class="" style="display: flex;">
									<input type="text" v-model="total_credit_limit_of_huabei" placeholder="请输入下单人花呗总额度"
										style="font-size: 25rpx;background-color: #f6f6f6;width: 280rpx;" />
								</view>
							</view>
						</view>
						<view class="tip">
							请填写真实花呗总额度，若未开通花呗或额度被冻结的，填写0
						</view>
					</view>
					<!-- 芝麻信用分 -->
					<view class="">
						<view class="priceItem">
							<view class="Pitem">
								<view class="">
									芝麻信用分：
								</view>
								<view class="" style="display: flex;">
									<input type="text" v-model="sesame_credit_score" placeholder="请输入芝麻信用分"
										style="font-size: 25rpx;background-color: #f6f6f6;width: 220rpx;" />
								</view>
							</view>
						</view>
						<view class="tip">
							请填写芝麻信用分
						</view>
					</view>
				</view>
				<view v-if="downpayCol.length > 0" :class="[downpayCol.length > 0?'mainBox':'']">
					<!-- 首付金额 -->
					<view class="downpayBox">
						<view class="" v-for="(item,index) in downpayCol" :key="index">
							<view :class="['downpayItem',active == index?'activeItem':'']"
								@click="changenDownpay(item,index)">
								{{item.name}}
							</view>
						</view>
					</view>
					<!-- 订单总额 -->
					<view class="" v-if="totlePrice && price && active !== -1">
						<view class="priceItem">
							<view class="Pitem">
								<view class="">
									订单总额：
								</view>
								<view class="">
									{{totlePrice}}
								</view>
							</view>
						</view>
						<view class="tip">
							订单总额：售价+服务费
						</view>
					</view>
				</view>
				<view class="mainBox" style="margin-bottom: 200rpx;" v-if="billData.length > 0">
					<view class="title">
						账单明细：
					</view>
					<view class="Pitem1" v-for="(item,index) in billData" :key="index">
						<view class="Pitem1Time">
							<span>{{item.name}}</span>
							<span>{{item.time}}</span>
						</view>
						<view class="">
							￥{{ ((item.price)*1).toFixed(2)}}
						</view>
					</view>
				</view>


			</view>
		</scroll-view>
		<!-- 底部 下一页 -->
		<view class="botBox" id="botBox">
			<view class="nextPage" @click="nextStep" v-if="token">
				下一页
			</view>
			<button v-else class="nextPage" @getAuthorize="onGetAuthorize1" open-type="getAuthorize" scope="phoneNumber"
				onError="handleAuthError">
				下一页
			</button>

		</view>
	</view>
</template>
<script>
	import {
		pay
	} from '@/common/pay.js';
	import baseurl from "@/config.js"
	export default {
		data() {
			return {
				baseurl: "",
				tabItemActive: false,
				token: '',
				// 以租代购标识  0 正常  4 以租代购
				car_lease: 1,
				// 品牌参数
				category_id: '',
				product_id: '',
				// 新旧机区别 0新机 1旧机
				new_machine: 1,
				// 商品指导价
				guide_price: '',
				// 商品售价
				ceiling_price: '',
				// tabs数据
				tabsList: [{
						name: '新机',
						value: 1
					},
					{
						name: '旧机',
						value: 2
					},
				],
				// 品牌数据
				brandCol: [],
				brandVal: 0,
				brandName: '请选择品牌',
				// 型号数据
				modelCol: [],
				modelVal: 0,
				modelName: '请选择型号',
				// 内存数据
				memoryCol: [],
				memoryVal: 0,
				memoryName: '请选择内存',
				// 首付金额数据
				downpayCol: [],
				downpayVal: 0,
				downpayName: '请选择购机优惠',
				// 账单明细
				billData: [],
				// 售价
				price: '',
				// 订单总额
				totlePrice: '',
				// 首单配置比例
				down_payment_ratio: '',
				// 末期自定义期数
				late: '',
				// 末期自定义期数金额
				rent: '',
				// 花呗总额度
				total_credit_limit_of_huabei: '',
				// 芝麻信用分
				sesame_credit_score: "",
				// 首付配置id
				down_payment: '',
				product_sku_id: '',
				old_and_new: '',
				active: -1,
				// 传递下单页面的新旧机参数 0 新机 1旧机
				old_and_new: '',
				// 接受商品规格
				skuData: [],
				// 不用内存不同的价格
				sku: [],
				scrollviewHigh: 0
			}
		},
		created() {
			this.getBrandData()
			if (uni.getStorageSync('token')) {
				this.token = uni.getStorageSync('token')
			}
			this.baseurl = baseurl.app_url;
			this.init()
		},
		watch: {
			price: {
				deep: true,
				handler: function(n, o) {
					if (n != o && o !== undefined) {
						this.break()
					}
				},
				immediate: true
			}
		},
		methods: {
			/*初始化*/
			init() {
				let _this = this;
				uni.getSystemInfo({
					success(res) {
						_this.phoneHeight = res.windowHeight;
						// 计算组件的高度
						let view = uni.createSelectorQuery().select('#botBox');
						let view1 = uni.createSelectorQuery().select('#main1');
						let h1 = ''
						view.boundingClientRect(data => {
							let h = _this.phoneHeight - data.height;
							h1 =  h
						}).exec();
						view1.boundingClientRect(data => {
							_this.scrollviewHigh = h1 - data.height;
							console.log(_this.scrollviewHigh,_this.phoneHeight,'=------asd');
						}).exec();
					}
				});
			},
			blurPrice() {
				let n = (this.price * 1).toFixed(2)
				if (Number(n) > Number(this.guide_price) && this.guide_price) {
					uni.showToast({
						title: '售价需小于等于最高售价'
					});
				}
			},
			// 切换新机旧机页面
			switchTabs(val) {
				// 1新机  2旧机
				// this.new_machine = val.value
				this.new_machine = val
				this.modelCol = []
				this.modelVal = 0
				this.modelName = '请选择型号'
				this.memoryCol = []
				this.memoryVal = 0
				this.memoryName = '请选择内存'
				this.price = ''
				this.guide_price = ''
				this.brandCol = []
				this.brandVal = 0
				this.brandName = '请选择品牌'
				this.billData = []
				this.downpayCol = []
				this.getBrandData()
			},
			// 获取品牌数据
			getBrandData() {
				let self = this;
				self._post('product.category/get_car_lease', {
						app_id: 10001,
						// 新旧机区分  1新机  2旧机
						old_and_new: self.new_machine
					},
					res => {
						self.brandCol = res.data.list_data;

					})
			},
			// 选择品牌类型
			changeBrand(e) {
				this.brandVal = e.detail.value
				// 切换了品牌类型
				if (this.brandName !== '请选择品牌' && this.brandCol[this.brandVal].name !== this.brandName) {
					this.modelCol = []
					this.modelVal = 0
					this.modelName = '请选择型号'
					this.memoryCol = []
					this.memoryVal = 0
					this.memoryName = '请选择内存'
					this.downpayCol = []
					this.billData = []
				}
				this.brandName = this.brandCol[this.brandVal].name
				this.category_id = this.brandCol[this.brandVal].category_id
				// 获取型号数据
				this.getModelData()
			},
			// 选择型号
			changeModel(e) {
				this.modelVal = e.detail.value
				this.modelName = this.modelCol[this.modelVal].model
				this.product_id = this.modelCol[this.modelVal].id
				this.memoryCol = []
				this.memoryVal = 0
				this.memoryName = '请选择内存'
				this.downpayCol = []
				this.billData = []
				// 获取内存信息
				this.getMemoryData()
			},
			// 获取型号数据
			getModelData() {
				let self = this
				self._post('product.product/lists', {
						app_id: 10001,
						category_id: self.category_id,
						car_lease: self.car_lease
					},
					res => {
						let data = res.data.list.data
						self.modelCol = []
						for (var i = 0; i < data.length; i++) {
							self.modelCol.push({
								id: data[i].product_id,
								model: data[i].product_desc
							})
						}

					})
			},
			// 选择内存
			changeMemory(e) {
				this.memoryVal = e.detail.value
				this.memoryName = this.memoryCol[this.memoryVal].memory
				this.product_sku_id = this.memoryCol[this.memoryVal].id + '_1'
				this.sku = this.skuData[this.memoryVal]
				// 商品指导价
				this.guide_price = this.sku.guide_price
				// 商品售价
				this.ceiling_price = this.sku.ceiling_price
			},
			// 获取内存数据
			getMemoryData() {
				let self = this
				self._post('product.product/detail', {
					app_id: 10001,
					product_id: self.product_id,
					url: '',
					visitcode: ''
				}, res => {
					// 内存规格相关数据
					self.skuData = res.data.detail.sku
					// 首付配置
					self.downpayCol = res.data.detail.configuration
					// 具体规格参数
					let data = res.data.specData.spec_attr;
					for (let i = 0; i < data.length; i++) {
						// 内存数据
						if (data[i].group_name == '内存') {
							let info = data[i].spec_items;
							self.memoryCol = []
							for (let s = 0; s < info.length; s++) {
								self.memoryCol.push({
									id: info[s].item_id,
									memory: info[s].spec_value
								})
							}
						}
					}
				})
			},
			// 选择首付金额
			changenDownpay(e, index) {
				this.active = index
				if (this.price) {
					// this.downpayVal = e.detail.value
					// this.downpayName = e.name
					// 首付配置id
					this.down_payment = e.id
					// 账单明细的长度
					// let billDataLength = this.downpayName.replace(/[^0-9]/g, "");
					let billDataLength = e.number_of_periods
					// 首单配置比例
					this.down_payment_ratio = e.down_payment_ratio
					// 末期自定义期数数量
					this.lateNum = e.late
					this.late = billDataLength - this.lateNum
					// 末期自定义期数金额
					this.rent = e.rent
					// 服务费用
					this.service = (e.service) / 100
					// this.price * this.down_payment_ratio
					this.billData.length = billDataLength
					// 获取订单总额  售价*（1+服务费用）
					this.totlePrice = (this.price * (1 + this.service)).toFixed(2)
					this.getBillData()
					console.log(this.billData, '=----this.billData');
				} else {
					uni.showToast({
						title: '请填写售价'
					});
				}
			},
			// 售价price刷新
			break () {
				this.totlePrice = (this.price * (1 + this.service)).toFixed(2)
				this.getBillData()
			},
			// 获取账单明细数据
			getBillData() {
				let time = new Date();
				for (let i = 0; i < this.billData.length; i++) {
					if (i == 0) {
						let obj = {
							name: '首期',
							price: (this.price * (this.down_payment_ratio / 100)).toFixed(2),
							time: this.getRecentMonth_Date(i)
						}
						this.billData[0] = obj
					}
					if (i >= this.late) {
						let obj1 = {
							name: '第' + (i + 1) + '期',
							price: (this.rent * 1).toFixed(2),
							time: this.getRecentMonth_Date(i)
						}
						this.billData[i] = obj1
					}
					if (i > 0 && i < this.late) {
						let obj2 = {
							name: '第' + (i + 1) + '期',
							//  5500-(500+100*3) / 12-(1+3)  5500-800/12-4   4700/8
							price: ((this.totlePrice - ((this.price * (this.down_payment_ratio / 100)) + (this.rent *
								this.lateNum))) / (this.billData.length - (1 + this.lateNum))).toFixed(2),
							time: this.getRecentMonth_Date(i)
						}
						this.billData[i] = obj2
					}
				}
			},
			getRecentMonth_Date(n) {
				let result = '';
				const datenow = new Date();
				const dateend =
					datenow.getFullYear().toString() +
					'-' +
					(datenow.getMonth() + 1).toString() +
					'-' +
					datenow.getDate().toString();
				datenow.setMonth(datenow.getMonth() + n);
				let dyear = datenow.getFullYear();
				let dmonth = datenow.getMonth() + 1;
				dmonth = dmonth < 10 ? 0 + dmonth : dmonth;
				let dday = datenow.getDate();
				const datestart =
					dyear.toString() + '-' + dmonth.toString() + '-' + dday.toString();
				result += datestart
				return result;
			},
			// 下一步 跳转页面
			nextStep() {
				if (!this.total_credit_limit_of_huabei) {
					uni.showToast({
						title: "请填写花呗总额度！",
						duration: 1000,
						position: 200,
					})
					return
				}
				if (!this.sesame_credit_score) {
					uni.showToast({
						title: "请填写芝麻信用分！",
						duration: 1000,
						position: 200,
					})
					return
				}
				if (!this.down_payment) {
					uni.showToast({
						title: "请选择首付金额！",
						duration: 1000,
						position: 200,
					})
					return
				}
				if (!this.price) {
					uni.showToast({
						title: "请填写售价！",
						duration: 1000,
						position: 200,
					})
					return
				}
				if (this.new_machine == 1) {
					this.old_and_new = 0
				} else if (this.new_machine == 2) {
					this.old_and_new = 1
				}
				uni.navigateTo({
					url: '/pages/order/leaseSubmit?price=' + this.price + '&down_payment=' + this.down_payment +
						'&sesame_credit_score=' + this.sesame_credit_score + '&total_credit_limit_of_huabei=' +
						this.total_credit_limit_of_huabei + '&car_lease=' + this.car_lease + '&product_id=' + this
						.product_id + '&product_num=' + 1 + '&product_sku_id=' + this.product_sku_id +
						'&old_and_new=' + this.old_and_new
				})
			},
			// 支付宝登录
			async onGetAuthorize1() {
				let tguser_id = uni.getStorageSync('tguser_id');
				// 获取授权码
				my.getAuthCode({
					scopes: ['auth_base'],
					success: (res) => {
						my.getPhoneNumber({
							success: (res1) => {
								let encryptedData = res1.response;
								encryptedData = JSON.parse(encryptedData);
								let response = encryptedData.response
								this._post('user.usermp/mnpAlipayAuthLogin', {
									code: res.authCode,
									content: response,
									tguser_id: tguser_id
								}, res => {
									if (res.data.code == 0) {
										uni.showToast({
											title: res.data.msg
										});
									} else {
										this.token = res.data.data.token
										uni.setStorageSync('token', res.data.data
											.token);
										uni.setStorageSync('user_id', res.data.data
											.user_id);
										uni.showToast({
											title: '登录成功'
										});
										this.nextStep()
									}
								})
							},
							fail: (res) => {
								console.log("失败")
								this.nextStep()
								reject(res);
							}
						});
					},
				});
			},
		},

		mounted() {},
		onLoad() {},
	}
</script>

<style lang="less">
	.page {
		background-color: #f3f3f3;
	}

	.downpayBox {
		display: flex;
		justify-content: flex-start;
		flex-wrap: wrap;
	}

	.downpayItem {
		background-color: #eef7fe;
		width: 190rpx;
		height: 70rpx;
		color: #14AAA8;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
	}

	.activeItem {
		background-color: #14AAA8;
		width: 190rpx;
		height: 70rpx;
		color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
	}

	.tabsBox {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 80rpx;
	}

	.tabsBox .tabItem {
		flex: 1;
		height: 100rpx;
		border-radius: 0px 0px 0px 0px;
		opacity: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		flex-direction: column;
		position: relative;
		background-color: #ffffff;
	}

	.tabItemClass {
		color: #14AAA8;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
	}

	.activeBox {
		width: 32rpx;
		height: 6rpx;
		opacity: 1;
		background-color: #14AAA8;
		position: absolute;
		bottom: 0;
	}

	.oldBox {}

	.mainBox {
		background-color: #ffffff;
		margin: 30rpx 20rpx;
		padding: 30rpx 30rpx;
	}

	.zhibaoTime {
		width: 136rpx;
		height: 80rpx;
		background: #14AAA8;
		border-radius: 12rpx;
		opacity: 1;
		font-weight: 600;
		color: #FFFFFF;
		font-size: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.tipBox {
		width: 662rpx;
		height: 208rpx;
		background-color: #FFF7E8;
		border-radius: 15rpx;
	}

	.tipTop {
		display: flex;
		padding-top: 10rpx;
	}

	.tipBot {
		width: 500rpx;
		font-size: 28rpx;
		font-weight: 400;
		color: #FF7D00;
		align-items: center;
		margin: 20rpx auto;
	}

	.tipBot1 {
		width: 300rpx;
		font-size: 28rpx;
		font-weight: 400;
		color: #FF7D00;
		align-items: center;
		margin: 20rpx auto;
	}

	.lefticon {
		width: 120rpx;
		height: 48rpx;
	}

	.lefticon image {
		width: 120rpx;
		height: 48rpx;
	}

	.title {
		height: 50rpx;
		font-size: 28rpx;
		font-weight: 500;
		color: rgba(0, 0, 0, 0.9);
		line-height: 44rpx;
	}

	.infoItem {
		width: 95%;
		height: 90rpx;
		font-size: 30rpx;
		border-radius: 10rpx;
		padding: 0 20rpx;
		background-color: #f6f6f6;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-top: 12rpx;
		border-bottom: 2rpx solid #f6f6f6;
	}

	.leftText {
		font-size: 32rpx;
		font-weight: 530;
		color: rgba(0, 0, 0, 0.9);
		line-height: 48rpx;
		width: 170rpx;
	}

	.guideText {
		font-size: 30rpx;
		font-weight: 400;
		color: rgba(0, 0, 0, 0.9);
		line-height: 40rpx;
	}

	.rightText {
		font-size: 32rpx;
		font-weight: 400;
		color: rgba(0, 0, 0, 0.4);
		line-height: 48rpx;
	}

	.priceItem {
		width: 100%;
		height: 70rpx;
		border-radius: 10rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-top: 12rpx;
	}

	.Pitem {
		background-color: #f6f6f6;
		flex: 1;
		border-radius: 10rpx;
		height: 90rpx;
		line-height: 70rpx;
		padding: 0 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 15rpx;
	}

	.Pitem1 {
		background-color: #f6f6f6;
		flex: 1;
		border-radius: 10rpx;
		height: 100rpx;
		line-height: 70rpx;
		padding: 0 30rpx;
		display: flex;
		justify-content: space-between;
		margin-top: 15rpx;
		font-size: 25rpx;
		align-items: center;
	}

	.Pitem1Time {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		justify-content: center;
	}

	.tip {
		color: #EF3723;
		font-size: 21rpx;
		margin: 22rpx;
	}

	.botBox {
		width: 100%;
		height: 180rpx;
		background-color: #ffffff;
		position: fixed;
		bottom: 0;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.nextPage {
		width: 90%;
		// border-radius: 40rpx;
		height: 80rpx;
		background-color: #3FD2CC;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #ffffff;
	}
</style>